<template>
  <el-drawer
    v-model="visible"
    :title="drawerTitle"
    direction="rtl"
    size="75%"
    @close="handleClose"
  >
    <el-form
      ref="orderFormRef"
      :model="orderForm"
      :rules="orderRules"
      label-width="100px"
      class="order-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="orderForm.orderNo" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="orderForm.supplierId" placeholder="请选择供应商" class="full-width" @change="handleSupplierChange">
              <el-option 
                v-for="supplier in suppliers" 
                :key="supplier.id" 
                :label="supplier.name" 
                :value="supplier.id" 
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="预计到货" prop="expectedDate">
            <el-date-picker
              v-model="orderForm.expectedDate"
              type="date"
              placeholder="请选择预计到货日期"
              class="full-width"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购员" prop="buyer">
            <el-input v-model="orderForm.buyer" placeholder="请输入采购员" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="orderForm.remark" 
          type="textarea" 
          :rows="2"
          placeholder="请输入备注信息" 
        />
      </el-form-item>

      <el-form-item label="商品明细">
        <div class="product-list">
          <div class="product-header">
            <el-button type="primary" size="small" @click="addProduct">
              <el-icon><Plus /></el-icon>
              添加商品
            </el-button>
          </div>
          <el-table :data="orderForm.products" border>
            <el-table-column prop="productCode" label="商品编码" width="120">
              <template #default="{ row, $index }">
                <el-input v-model="row.productCode" placeholder="商品编码" @blur="loadProductInfo(row, $index)" />
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" width="200">
              <template #default="{ row, $index }">
                <el-input v-model="row.productName" placeholder="商品名称" />
              </template>
            </el-table-column>
            <el-table-column prop="specification" label="规格" width="150">
              <template #default="{ row, $index }">
                <el-input v-model="row.specification" placeholder="规格" />
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="80">
              <template #default="{ row, $index }">
                <el-input v-model="row.unit" placeholder="单位" />
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100">
              <template #default="{ row, $index }">
                <el-input-number 
                  v-model="row.quantity" 
                  :min="1" 
                  class="full-width"
                  @change="calculateAmount"
                />
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template #default="{ row, $index }">
                <div class="price-input">
                  <el-input-number 
                    v-model="row.unitPrice" 
                    :min="0" 
                    :precision="2"
                    class="price-number"
                    @change="calculateAmount"
                  />
                  <el-button 
                    type="primary" 
                    size="small" 
                    class="price-compare-btn"
                    @click="showPriceComparison(row, $index)"
                  >
                    比价
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="100">
              <template #default="{ row }">
                ¥{{ (row.quantity * row.unitPrice).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ $index }">
                <el-button type="danger" size="small" @click="removeProduct($index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="total-amount">
            <span>订单总额：<strong>¥{{ orderForm.totalAmount.toFixed(2) }}</strong></span>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </div>
    </template>

    <!-- 价格对比对话框 -->
    <el-dialog
      v-model="priceComparisonVisible"
      title="供应商价格对比"
      width="800px"
    >
      <div v-if="currentProduct">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品编码">{{ currentProduct.productCode }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ currentProduct.productName }}</el-descriptions-item>
          <el-descriptions-item label="规格">{{ currentProduct.specification }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ currentProduct.unit }}</el-descriptions-item>
        </el-descriptions>

        <el-divider>供应商报价对比</el-divider>
        <el-table :data="priceComparisonData" border>
          <el-table-column prop="supplierName" label="供应商" width="150" />
          <el-table-column prop="unitPrice" label="单价" width="120">
            <template #default="{ row }">
              ¥{{ row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="minOrder" label="最小起订量" width="120" />
          <el-table-column prop="deliveryTime" label="交货期" width="100" />
          <el-table-column prop="rating" label="供应商评级" width="120">
            <template #default="{ row }">
              <el-rate 
                v-model="row.rating" 
                disabled 
                show-score 
                text-color="#ff9900"
              />
            </template>
          </el-table-column>
          <el-table-column prop="lastOrderDate" label="上次采购时间" width="150" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click="selectSupplier(row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="closePriceComparison">关闭</el-button>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  suppliers: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'submit', 'close'])

// 响应式数据
const visible = ref(false)
const submitLoading = ref(false)
const orderFormRef = ref()
const currentProduct = ref(null)
const currentProductIndex = ref(-1)
const priceComparisonVisible = ref(false)

// 订单表单
const orderForm = reactive({
  id: null,
  orderNo: '',
  supplierId: '',
  supplierName: '',
  totalAmount: 0,
  expectedDate: '',
  buyer: '',
  remark: '',
  products: []
})

// 表单验证规则
const orderRules = {
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  expectedDate: [
    { required: true, message: '请选择预计到货日期', trigger: 'change' }
  ],
  buyer: [
    { required: true, message: '请输入采购员', trigger: 'blur' }
  ]
}

// 价格对比数据
const priceComparisonData = ref([
  {
    supplierName: '苹果供应商',
    unitPrice: 5000,
    minOrder: 1,
    deliveryTime: '7天',
    rating: 4.5,
    lastOrderDate: '2024-01-10'
  },
  {
    supplierName: '华为供应商',
    unitPrice: 4800,
    minOrder: 5,
    deliveryTime: '10天',
    rating: 4.3,
    lastOrderDate: '2024-01-05'
  },
  {
    supplierName: '小米供应商',
    unitPrice: 5200,
    minOrder: 3,
    deliveryTime: '5天',
    rating: 4.1,
    lastOrderDate: '2024-01-08'
  }
])

// 计算属性
const isEdit = computed(() => !!orderForm.id)
const drawerTitle = computed(() => isEdit.value ? '编辑订单' : '新建订单')

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    resetForm()
    if (!isEdit.value) {
      generateOrderNo()
    }
  }
})

// 监听 visible 变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 方法
const handleSupplierChange = (supplierId) => {
  const supplier = props.suppliers.find(s => s.id === supplierId)
  if (supplier) {
    orderForm.supplierName = supplier.name
  }
}

const addProduct = () => {
  orderForm.products.push({
    productCode: '',
    productName: '',
    specification: '',
    unit: '',
    quantity: 1,
    unitPrice: 0
  })
}

const removeProduct = (index) => {
  orderForm.products.splice(index, 1)
  calculateAmount()
}

const calculateAmount = () => {
  orderForm.totalAmount = orderForm.products.reduce((total, product) => {
    return total + (product.quantity * product.unitPrice)
  }, 0)
}

const generateOrderNo = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
  orderForm.orderNo = `PO${year}${month}${day}${random}`
}

const loadProductInfo = (row, index) => {
  if (row.productCode) {
    // 模拟根据商品编码加载商品信息
    const mockProductInfo = {
      'P001': {
        productName: 'iPhone 15',
        specification: '128GB 黑色',
        unit: '台',
        unitPrice: 5000
      },
      'P002': {
        productName: 'MacBook Pro',
        specification: '13英寸 M2芯片',
        unit: '台',
        unitPrice: 12000
      },
      'P003': {
        productName: 'Nike运动鞋',
        specification: '42码 白色',
        unit: '双',
        unitPrice: 400
      }
    }
    
    const productInfo = mockProductInfo[row.productCode]
    if (productInfo) {
      row.productName = productInfo.productName
      row.specification = productInfo.specification
      row.unit = productInfo.unit
      row.unitPrice = productInfo.unitPrice
      calculateAmount()
    }
  }
}

const showPriceComparison = (row, index) => {
  currentProduct.value = row
  currentProductIndex.value = index
  priceComparisonVisible.value = true
}

const selectSupplier = (supplier) => {
  if (currentProduct.value && currentProductIndex.value >= 0) {
    orderForm.products[currentProductIndex.value].unitPrice = supplier.unitPrice
    calculateAmount()
    ElMessage.success(`已选择 ${supplier.supplierName} 的报价`)
    priceComparisonVisible.value = false
  }
}

const closePriceComparison = () => {
  priceComparisonVisible.value = false
}

const handleSubmit = async () => {
  if (!orderFormRef.value) return

  try {
    await orderFormRef.value.validate()
    
    if (orderForm.products.length === 0) {
      ElMessage.warning('请至少添加一个商品')
      return
    }

    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 发送提交事件
    emit('submit', { ...orderForm })

    ElMessage.success(isEdit.value ? '编辑成功' : '新建成功')
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleClose = () => {
  visible.value = false
  emit('close')
}

const resetForm = () => {
  Object.assign(orderForm, {
    id: null,
    orderNo: '',
    supplierId: '',
    supplierName: '',
    totalAmount: 0,
    expectedDate: '',
    buyer: '',
    remark: '',
    products: []
  })
  orderFormRef.value?.clearValidate()
}

// 暴露方法给父组件
defineExpose({
  open: (orderData = null) => {
    if (orderData) {
      Object.assign(orderForm, { ...orderData })
    } else {
      resetForm()
      generateOrderNo()
    }
    visible.value = true
  },
  close: handleClose
})
</script>

<style scoped>
.order-form {
  padding: 20px;
}

.product-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.product-header {
  margin-bottom: 10px;
}

.total-amount {
  margin-top: 10px;
  text-align: right;
  font-size: 16px;
  color: #e6a23c;
}

.price-input {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.price-number {
  width: 100%;
}

.price-compare-btn {
  margin-top: 4px;
}

.full-width {
  width: 100%;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
}
</style>
